package cn.hengzhu.main_manager.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * 增删改AJax请求想要Json所对的类
 *   只关心是否成功及失败后的提示
 * @author Administrator
 *
 */
public class ToolsUtils {

	public static String valueOfStr(Object obj) {
		return (obj == null) ? "" : obj.toString().trim();
	}
	
	public static String valueOfNull(Object obj) {
		
		if(obj == null || obj.toString().trim().equals("")){
			return null;
		}
		return obj.toString().trim();
	}
	
	public static Object objectValueOfStr(Object obj) {
		Class<?> clazz = obj.getClass();
		Field[] declaredFields = clazz.getDeclaredFields();
		for (Field field : declaredFields) {
			field.setAccessible(true);
			try {
				 if(!Modifier.isStatic(field.getModifiers())&&isBaseType(field.getType(),true)){
					String str = valueOfStr(field.get(obj));
					Class<?> type = field.getType();
					if(type == Integer.class || type==int.class){
						int i = Integer.parseInt(str);
						field.set(obj, i);
					}else if(type == long.class || type==Long.class){
						long l = Long.parseLong(str);
						field.set(obj, l);
					}else{
						field.set(obj, str);
					}
				}
				
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return obj;
	}
	/**
	 * 判断对象属性是否是基本数据类型,包括是否包括string
	 * @param className
	 * @param incString 是否包括string判断,如果为true就认为string也是基本数据类型
	 * @return
	 */
	public static boolean isBaseType(Class<?> className, boolean incString) {
	    if (incString && className.equals(String.class)) {
	        return true;
	    }
	    return className.equals(Integer.class) ||className.equals(int.class) ||
	            className.equals(Byte.class) ||className.equals(byte.class) ||
	            className.equals(Long.class) ||className.equals(long.class) ||
	            className.equals(Double.class) ||className.equals(double.class) ||
	            className.equals(Float.class) ||className.equals(float.class) ||
	            className.equals(Character.class) || className.equals(char.class) ||
	            className.equals(Short.class) ||className.equals(short.class) ||
	            className.equals(Boolean.class) ||className.equals(boolean.class);
	}
}
